import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import { ProFormText } from '@ant-design/pro-form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddFrom from './components/AddForm';
import type {
  TenantAddItem,
  TenantChangeBelongBean,
  TenantChangeRoleBean,
  TenantItem,
  TenantUpdateItem,
} from './data.d';
import {
  addTenant,
  changeTenantBelong,
  changeTenantRole,
  deleteTenant,
  queryTenantListByAdmin,
  updateTenant,
} from './service';
import EditTenantRoleForm from './components/EditTenantRoleForm';
import EditTenantInfoForm from './components/EditTenantInfoForm';
import EditTenantBelongForm from './components/EditTenantBelongForm';
import { useModel } from 'umi';

const TenantTableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'TENANT.ADD': add,
    'TENANT.CHANGE.ROLE': change,
    'TENANT.DELETE': Delete,
    'TENANT.EDIT.BELONG': edit,
    'TENANT.UPDATE': update,
  } = currUser;

  const [sorter, setSorter] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [editRoleVisible, setEditRoleVisible] = useState<boolean>(false);
  const [editInfoVisible, setEditInfoVisible] = useState<boolean>(false);
  const [changeBelongVisible, setChangeBelongVisible] = useState<boolean>(false);
  const [tenant, setTenant] = useState<TenantItem | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: TenantAddItem) {
    const hide = message.loading('正在添加');

    const res = await addTenant(fields);
    hide();
    if (res.code === SUCCESS_CODE) {
      message.success(res.message || '添加成功');
      actionRef.current?.reload();
    } else {
      message.error(res.message || '添加失败请重试！');
    }
    handleAddModalVisible(false);
  }

  // 删除
  const handleRemove = async (id: string) => {
    const hide = message.loading('正在删除');
    try {
      await deleteTenant(id);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const editRoleEvent = async (values: TenantChangeRoleBean) => {
    const res = await changeTenantRole(values);
    if (res.code === SUCCESS_CODE) {
      setEditRoleVisible(false);
      message.success(res.message);
      actionRef.current?.reload();
    } else {
      message.error(res.message);
    }
  };

  const editInfoEvent = async (values: TenantUpdateItem) => {
    const res = await updateTenant(values);
    if (res.code === SUCCESS_CODE) {
      setEditInfoVisible(false);
      message.success(res.message);
      actionRef.current?.reload();
    } else {
      message.error(res.message);
    }
  };

  const changeBelongEvent = async (values: TenantChangeBelongBean) => {
    const res = await changeTenantBelong(values);
    if (res.code === SUCCESS_CODE) {
      setChangeBelongVisible(false);
      message.success(res.message);
      actionRef.current?.reload();
    } else {
      message.error(res.message);
    }
  };

  const columns: ProColumns<TenantItem>[] = [
    {
      title: '客户编号',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '客户名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: 'appid',
      dataIndex: 'appid',
      ellipsis: true,
      search: false,
    },
    {
      title: 'secret',
      dataIndex: 'secret',
      ellipsis: true,
      search: false,
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      ellipsis: true,
      search: false,
    },
    {
      title: '推送地址',
      dataIndex: 'push_url',
      ellipsis: true,
      search: false,
    },
    {
      title: '联系方式',
      dataIndex: 'mobile',
      ellipsis: true,
      search: false,
    },
    {
      title: '邮箱',
      dataIndex: 'mail',
      ellipsis: true,
      search: false,
    },
    {
      title: '所属权',
      dataIndex: 'belong',
      ellipsis: true,
      render: (_, record) => {
        return record.belong_name;
      },
      renderFormItem: () => {
        return <ProFormText placeholder="请输入所属管理员id" />;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除客户 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除客户</p>
                <span>{name}</span>?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove(id);
            },
            centered: true,
            width: '30vw',
            style: { height: '18vw' },
          });
        };

        return (
          <div>
            {change && (
              <a
                onClick={() => {
                  setEditRoleVisible(true);
                  setTenant(record);
                }}
              >
                修改角色
              </a>
            )}
            {update && (
              <>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    setEditInfoVisible(true);
                    setTenant(record);
                  }}
                >
                  编辑
                </a>
              </>
            )}
            {edit && (
              <>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    setChangeBelongVisible(true);
                    setTenant(record);
                  }}
                >
                  修改所属权
                </a>
              </>
            )}
            {Delete && (
              <>
                <Divider type="vertical" />
                <a onClick={onClickRemove}>删除</a>
              </>
            )}
          </div>
        );
      },
    },
  ];
  return (
    <PageHeaderWrapper title="客户管理">
      <ProTable<TenantItem>
        headerTitle={'客户管理列表'}
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TenantItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <>
            {add && (
              <Button type="primary" key={''} onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined /> 添加
              </Button>
            )}
          </>,
        ]}
        tableAlertRender={() => false}
        request={(params) => {
          return queryTenantListByAdmin(params);
        }}
        columns={columns}
        rowSelection={false}
      />
      {addModalVisible && (
        <AddFrom
          modalVisible={addModalVisible}
          onSubmit={(value) => handleAdd(value)}
          onCancel={() => handleAddModalVisible(false)}
        />
      )}
      {editRoleVisible && tenant && (
        <EditTenantRoleForm
          tenant={tenant}
          onSubmit={editRoleEvent}
          onCancel={() => setEditRoleVisible(false)}
          visibleHandler={() => setEditRoleVisible(false)}
          modalVisible={editRoleVisible}
        />
      )}
      {editInfoVisible && tenant && (
        <EditTenantInfoForm
          tenant={tenant}
          onSubmit={editInfoEvent}
          onCancel={() => setEditInfoVisible(false)}
          visibleHandler={() => setEditInfoVisible(false)}
          modalVisible={editInfoVisible}
        />
      )}
      {changeBelongVisible && tenant && (
        <EditTenantBelongForm
          tenant={tenant}
          onSubmit={changeBelongEvent}
          onCancel={() => setChangeBelongVisible(false)}
          visibleHandler={() => setChangeBelongVisible(false)}
          modalVisible={changeBelongVisible}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TenantTableList;
